package com.ls.markt.service.admin;

import com.ls.markt.dao.admin.PlayerMapper;
import com.ls.markt.dto.PlayerImportDTO;
import com.ls.markt.model.admin.Player;
import com.ls.markt.repository.admin.PlayerRepository;
import com.ls.markt.util.ExcelUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service
public class PlayerService {

    @Resource
    private PlayerMapper mapper;

    @Resource
    private PlayerRepository playerRepository;

    @Resource
    private ClubService clubService;

    /**
     * 分页查询全部
     * @param pageRequest
     * @return
     */
    public Page<Player> findAll(PageRequest pageRequest) {
        return playerRepository.findAll(pageRequest);
    }

    public void savePlayer(Player player) {
        playerRepository.save(player);
    }

    public Player getPlayerById(Long id) {
        return playerRepository.getOne(id);
    }

    public void removePlayer(Long[] ids) {
        for (Long id:ids){
            playerRepository.deleteById(id);
        }
    }

    public List<Player> listPlayersByClubId(Long clubId) {
        return playerRepository.findByClub(clubId);
    }

    public Map<String, Object> listInfoByClub(Long clubId) {
        return mapper.findInfoByClub(clubId);
    }

    /**
     * 根据赛事查询球员人数
     * @param level
     * @return
     */
    public int getPlayerNumberByLevel(Long level){
        return mapper.getPlayerNumberByLevel(level);
    }

    public void importExcel(MultipartFile file) throws IOException {
        List<Object> playerDTOs = ExcelUtil.readExcel(file, PlayerImportDTO.class);
        for (Object o: playerDTOs){
            PlayerImportDTO playerImportDTO = (PlayerImportDTO) o;
            String clubName = playerImportDTO.getClubName();
            Long clubId = clubService.getIdByName(clubName);
            if (clubId!=null){
                Player player = new Player();
                BeanUtils.copyProperties(playerImportDTO,player);
                player.setClub(clubId);
                playerRepository.save(player);
            }
//            playerRepository.save(player);
        }
    }
}
